﻿<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
	<!--_meta 作为公共模版分离出去-->
	<meta charset="utf-8">
	<meta name="renderer" content="webkit|ie-comp|ie-stand">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
	<meta http-equiv="Cache-Control" content="no-siteapp" />
	<link rel="Bookmark" href="admin/images/rookieCs.ico" />
	<link rel="Shortcut Icon" href="admin/images/rookieCs.ico" />
	<!--[if lt IE 9]>
	<script type="text/javascript" src="admin/lib/html5.js"></script>
	<script type="text/javascript" src="admin/lib/respond.min.js"></script>
	<![endif]-->
	<link rel="stylesheet" type="text/css" href="admin/static/h-ui/css/H-ui.min.css" />
	<link rel="stylesheet" type="text/css" href="admin/static/h-ui.admin.pro.iframe/css/h-ui.admin.pro.iframe.min.css" />
	<link rel="stylesheet" type="text/css" href="admin/lib/Hui-iconfont/1.0.9/iconfont.css" />
	<link rel="stylesheet" type="text/css" href="admin/static/h-ui.admin.pro.iframe/skin/default/skin.css" id="skin" />
	<link rel="stylesheet" type="text/css" href="admin/static/business/css/style.css" />
	<!--[if IE 6]>
	<script type="text/javascript" src="http://lib.h-ui.net/DD_belatedPNG_0.0.8a-min.js" ></script>
	<script>DD_belatedPNG.fix('*');</script>
	<![endif]-->
    <script type="text/javascript" src="admin/lib/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="admin/lib/layer/3.1.1/layer.js"></script>
    <script type="text/javascript" src="admin/static/h-ui/js/H-ui.min.js"></script>
    <script type="text/javascript" src="admin/lib/jquery.contextmenu/jquery.contextmenu.r2.js"></script>
	<!--/meta 作为公共模版分离出去-->

	<title>江苏亦珣crm管理系统</title>
    <script type="text/javascript" src="admin/js/common.js"></script>
    <script type="text/javascript" src="admin/js/formatter.js"></script>
    <script type="text/javascript" src="admin/js/sockjs.min.js"></script>
    <script type="text/javascript" src="admin/js/stomp.min.js"></script>
</head>
<body>
	<!--_menu 作为公共模版分离出去-->
	<aside class="Hui-admin-aside-wrapper">
		<div class="Hui-admin-logo-wrapper">
			<a class="logo navbar-logo">
				<i class="va-m iconpic global-logo"></i>
				<span class="va-m" id="project_name">江苏亦珣crm</span>
			</a>
		</div>
		<div class="Hui-admin-menu-dropdown bk_2">
			<!--菜单信息-->
		</div>
	</aside>
	<div class="Hui-admin-aside-mask"></div>
	<!--/_menu 作为公共模版分离出去-->

	<div class="Hui-admin-dislpayArrow">
		<a href="javascript:void(0);" onClick="displaynavbar(this)">
			<i class="Hui-iconfont Hui-iconfont-left">&#xe6d4;</i>
			<i class="Hui-iconfont Hui-iconfont-right">&#xe6d7;</i>
		</a>
	</div>

	<section class="Hui-admin-article-wrapper">
		<!--_header 作为公共模版分离出去-->
		<header class="Hui-navbar">
			<div class="navbar">
				<div class="container-fluid clearfix">
                    <nav id="Hui-userbar" class="nav navbar-nav navbar-userbar">
                        <ul class="clearfix">
                            <li id="userRole"></li>
							<li class="dropDown dropDown_hover" style="z-index: 9999">
                                <a class="dropDown_A" id="userAccount"><i class="Hui-iconfont">&#xe6d5;</i></a>
                                <ul class="dropDown-menu menu radius box-shadow">
                                    <li><a onclick="editPassword()">修改密码</a></li>
									<li><a onclick="logout()">退出</a></li>
								</ul>
                            </li>
                            <li id="Hui-msg">
                                <a href="#" onclick="message()" title="消息">
                                    <span class="badge badge-danger" id="messageCount">0</span>
                                    <i class="Hui-iconfont" style="font-size:18px">&#xe68a;</i>
                                </a>
                            </li>
                            <li id="Hui-skin" class="dropDown dropDown_hover right">
                                <a href="javascript:;" class="dropDown_A" title="换肤"><i class="Hui-iconfont" style="font-size:18px">&#xe62a;</i></a>
                                <ul class="dropDown-menu menu radius box-shadow">
                                    <li><a href="javascript:;" data-val="default" title="默认（蓝色）">默认（深蓝）</a></li>
                                    <li><a href="javascript:;" data-val="black" title="黑色">黑色</a></li>
                                    <li><a href="javascript:;" data-val="green" title="绿色">绿色</a></li>
                                    <li><a href="javascript:;" data-val="red" title="红色">红色</a></li>
                                    <li><a href="javascript:;" data-val="yellow" title="黄色">黄色</a></li>
                                    <li><a href="javascript:;" data-val="orange" title="橙色">橙色</a></li>
                                </ul>
                            </li>
						</ul>
                    </nav>
                </div>
			</div>
		</header>
		<!--/_header 作为公共模版分离出去-->

		<div id="Hui-admin-tabNav" class="Hui-admin-tabNav">
			<div class="Hui-admin-tabNav-wp">
				<ul id="min_title_list" class="acrossTab clearfix" style="width: 241px; left: 0px;">
					<li class="active"><span title="我的桌面" data-href="welcome.html">我的桌面</span><em></em></li>
				</ul>
			</div>
			<div class="Hui-admin-tabNav-more btn-group" style="display: none;">
				<a id="js-tabNav-prev" class="btn radius btn-default size-S" href="javascript:;"><i class="Hui-iconfont">&#xe6d4;</i></a>
				<a id="js-tabNav-next" class="btn radius btn-default size-S" href="javascript:;"><i class="Hui-iconfont">&#xe6d7;</i></a>
			</div>
		</div>

		<div id="iframe_box" class="Hui-admin-article">
			<div class="show_iframe">
				<iframe id="iframe-welcome" data-scrolltop="1" scrolling="yes" frameborder="0" src="welcome.html"></iframe>
			</div>
		</div>
	</section>
	<div class="contextMenu" id="Huiadminmenu">
		<ul>
			<li id="closethis">关闭当前 </li>
			<li id="closeall">关闭全部 </li>
		</ul>
	</div>
</body>
<script type="text/javascript">
	var lockReconnect = false;//避免ws重复连接
	var backlogSocket = null;// 判断当前浏览器是否支持WebSocket
	var backlogSocketUrl = getRootPath().replace("http","ws") + "/backlogSocket";
	var reconnectCount = 0;//重连次数
    $(function () {
        getUserInfo();
        getUserMenus();
		// createWebSocket();
    });

    //查看版本更新记录
    function showVersionLog() {
        creatIframe("version-log.html", "版本更新记录");
    }

    //获取用户信息
    function getUserInfo() {
    	ajaxGetFun("user/getLoginInfo", {}, function(bizData) {
			$("#userRole").html(bizData.role.name);
			$("#userAccount").html(bizData.account + '<i class="Hui-iconfont">&#xe6d5;</i>');
			if (bizData.isRset) {
				layer.confirm('该密码已重置，请重新修改密码',function(index) {
					editPassword();
				});
			}
			sessionStorage.setItem("userId", bizData.id);
			sessionStorage.setItem("roleId", bizData.roleId);
			sessionStorage.setItem("roleType", bizData.role.roleType);
			if (bizData.role.pId <= 4) {
				sessionStorage.setItem("isSup", true);
			} else {
				sessionStorage.setItem("isSup", false);
			}
			sessionStorage.setItem("sessionUuid", bizData.sessionUuid);
		}, null, "获取用户信息", false);
    }

    //获取用户权限列表
    function getUserMenus() {
		ajaxGetFun("user/getUserMenus", {}, function(bizData) {
			var html = "";
			for (var i=0; i<bizData.length; i++) {
				html +=
						'<dl id="'+ bizData[i].url +'" class="Hui-menu">' +
						'	<dt class="Hui-menu-title"><i class="Hui-iconfont">'+ bizData[i].iconCode +'</i>'+ bizData[i].name +'<i class="Hui-iconfont Hui-admin-menu-dropdown-arrow">&#xe6d5;</i><div></div></dt>' +
						'	<dd class="Hui-menu-item">' +
						'		<ul>';
				var childrenList = bizData[i].children;
				for (var j=0; j<childrenList.length; j++) {
					html += '<li><a data-href="'+ childrenList[j].url +'" data-title="'+ childrenList[j].name +'">'+ childrenList[j].name +'</a><div id="'+childrenList[j].backlogKey+'"></div></li>'
				}
				html +=
						'		</ul>' +
						'	</dd>' +
						'</dl>';
			}
			$('.Hui-admin-menu-dropdown').html(html);
			jQuery.getScript("admin/static/h-ui.admin.pro.iframe/js/h-ui.admin.pro.iframe.min.js");
		}, null, "获取用户菜单列表", false);
    }

    //创建Socket
    function createWebSocket() {
		try {
			if ("WebSocket" in window) {
				backlogSocket = new WebSocket(backlogSocketUrl);
			}
			initEventHandle();
		} catch (e) {
			reconnect();
		}
	}

	//监听Socket
	function initEventHandle() {
		backlogSocket.onclose = function (info) {
		    console.log("连接被关闭"+ info);
			reconnect();
		};
		backlogSocket.onerror = function (info) {
            console.log("连接发生异常"+ info);
			reconnect();
		};
		backlogSocket.onopen = function () {
			heartCheck.reset().start();//心跳检测重置
		};
		backlogSocket.onmessage = function(event) {
			heartCheck.reset().start();//拿到任何消息都说明当前连接是正常的
			let message = event.data;
			if (message !== "pong") {
                let jsonObj = JSON.parse(message);
                if (jsonObj.key === "login" && jsonObj.value !== sessionStorage.getItem("sessionUuid")) {
                    sessionStorage.setItem("forcedLogout", dates("Y年m月d日 H时i分s", new Date()));
                    logout();
                } else if (jsonObj.key === "disableUser") {
                    sessionStorage.setItem("disabledLogout", dates("Y年m月d日 H时i分s", new Date()));
                    logout();
                } else if (jsonObj.key === "message") {
                    if (jsonObj.value > 0) {
                        $("#messageCount").show();
                        $("#messageCount").html(jsonObj.value);
                        showNotification(jsonObj);
                        playSound();
                    } else {
                        $("#messageCount").hide();
                    }
                } else if (jsonObj.value > 0) {
                    $("#" + jsonObj.key).html('<span class="badge badge-danger radius" style="float: right; margin-top: -30px; margin-right: 10px;">' + jsonObj.value + '</span>');
                    showNotification(jsonObj);
                    playSound();
                    backlog($("#" + jsonObj.key));
                } else {
                    $("#" + jsonObj.key).html('');
                    backlog($("#" + jsonObj.key));
                }
			}
		};
	}

    //重连Socket
	function reconnect() {
		if (!lockReconnect) {
		    if (reconnectCount >= 10) {
                sessionStorage.setItem("socket_closed", dates("Y年m月d日 H时i分s", new Date()));
                logout();
			} else {
                reconnectCount ++;
                lockReconnect = true;
                setTimeout(function() {//没连接上会一直重连，设置延迟避免请求过多
                    createWebSocket();
                    lockReconnect = false;
                }, 2000);
			}
		}
	}

	//心跳检测
	var heartCheck = {
		timeout: 60*1000,//1分钟发一次心跳
		timeoutObj: null,
		serverTimeoutObj: null,
		reset: function() {
			clearTimeout(this.timeoutObj);
			clearTimeout(this.serverTimeoutObj);
			return this;
		},
		start: function() {
			let self = this;
			this.timeoutObj = setTimeout(function() {
				//这里发送一个心跳，后端收到后，返回一个心跳消息，
				backlogSocket.send("ping");
				self.serverTimeoutObj = setTimeout(function() {//如果超过一定时间还没重置，说明后端主动断开了
				    console.log("主动断开了连接");
					backlogSocket.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
				}, self.timeout)
			}, this.timeout)
		}
	};
	
	//开启通知授权
	function showNotification(jsonObj) {
		if (!("Notification" in window)) {
			return showWarnMsg("您当前的浏览器不支持消息通知功能，继续使用将无法收到消息通知！");
		} else if (Notification.permission === "granted") {//检查用户是否同意接受通知
			var notification = new Notification("来消息了", {
				body: jsonObj.key === "message" ? "您有一条新的未读消息，点击可前往查看！" : "您有一条新的待办消息，点击可前往查看！",
				icon: getRootPath() + "/admin/images/rookieCs.ico"
			});
			notification.onclick = function() {
				window.focus();//打开对应的页面
				notification.close();//关闭提示信息
			};
			//定时关闭
			notification.onshow = function () {//定时关闭
				setTimeout(notification.close.bind(notification), 5000);
			}
		} else if (Notification.permission !== 'denied') {//否则我们需要向用户获取权限
			Notification.requestPermission(function (permission) {
				//如果用户同意，就可以向他们发送通知
				if (permission === "granted") {
					var notification = new Notification("来消息了", {
						body: jsonObj.key === "message" ? "您有一条新的未读消息，点击可前往查看！" : "您有一条新的待办消息，点击可前往查看",
						icon: getRootPath() + "/admin/images/rookieCs.ico"
					});
					notification.onclick = function() {
						window.focus();//打开对应的页面
						notification.close();//关闭提示信息
					};
					//定时关闭
					notification.onshow = function () {//定时关闭
						setTimeout(notification.close.bind(notification), 5000);
					}
				}
			});
		}
	}

    //播放提示音
    function playSound() {
        var borswer = window.navigator.userAgent.toLowerCase();
        if ( borswer.indexOf( "ie" ) >= 0 ) {
            //IE内核浏览器
            var strEmbed = '<embed name="embedPlay" src="admin/js/message.wav" autostart="true" hidden="true" loop="false"></embed>';
            if ( $( "body" ).find( "embed" ).length <= 0 )
                $( "body" ).append( strEmbed );
            var embed = document.embedPlay;

            //浏览器不支持 audion，则使用 embed 播放
            embed.volume = 100;
        } else {
            //非IE内核浏览器
            var strAudio = "<audio id='audioPlay' src='admin/js/message.wav' hidden='true' />";
            if ( $( "body" ).find( "audio" ).length <= 0 ) {
				$( "body" ).append( strAudio );
			}
            document.getElementById("audioPlay").play();
        }
    }

    function backlog(ele) {
		var dlEle = $(ele).parents("dl");
		var dtEle = dlEle.children("dt");
		var liEles = dlEle.children("dd").children("ul").children("li");
		var backlog = 0;
		for (var i=0; i<liEles.length; i++) {
		    if ($(liEles[i]).children("div").children("span").length > 0) {
                backlog += Number($(liEles[i]).children("div").children("span").html());
            }
		}
		if (backlog === 0) {
            dtEle.children("div").html('');
		} else {
            dtEle.children("div").html('<span class="badge badge-danger radius" style="float: right; margin-top: -30px; margin-right: 45px;">'+ backlog +'</span>');
		}
    }

    //修改密码
    function editPassword() {
        openIframe(false, 500, 200, "update-password.html", function() {}, function(index, layero) {
			var formEle = layero.find("iframe")[0].contentWindow.$("#formInfo");
			if (formEle.form("validate")) {
				var userInfo = getFormJson(formEle);
				if (userInfo.newPassword !== userInfo.confirmPassword) {
					showWarnMsg("两次输入的密码不一样");
				} else {
					userInfo.userId = sessionStorage.getItem("user_id");
					ajaxPostFun("user/updateUserPassword", userInfo, function() {
						layer.close(index);
						showSuccessMsg("修改成功");
						setTimeout(logout, 2000);
					}, null, "修改密码");
				}
			}
		});
    }

    //退出登录
    function logout() {
        ajaxPostFun("user/logout", {}, function(bizData) {
			window.location.href = "login.html";
		}, null, "退出系统");
    }

    //消息
    function message(){
        creatIframe("message-list.html","我的消息");
    }
</script>
</html>
